package ljt.music.module.tab3;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import java.util.List;

import ljt.music.R;
import ljt.music.bean.PlayList;
import ljt.music.bean.UserList;
import ljt.music.ui.playlist.PlayListAdapter;

/**
 * @author jiangtao
 * @date 2018/1/3
 */

public class UserListAdapter extends RecyclerView.Adapter<UserListAdapter.UserListHolder> {

  private Context context;
  private UserList userList;
  private UserListAdapter.OnItemClickLitener mOnItemClickLitener;
  private List<UserList.PlaylistBean> playlist;

  public UserListAdapter(Context context) {
    this.context = context;
  }

  public UserList getUserList() {
    return userList;
  }

  public void setUserList(UserList userList) {
    this.userList = userList;
    playlist = userList.getPlaylist();
    if (playlist != null) {
      notifyDataSetChanged();
    }
  }

  public interface OnItemClickLitener {
    void onItemClick(View view, int position);

    void onItemLongClick(View view, int position);
  }

  public void setOnItemClickLitener(UserListAdapter.OnItemClickLitener mOnItemClickLitener) {
    this.mOnItemClickLitener = mOnItemClickLitener;
  }

  @Override
  public UserListHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    return new UserListAdapter.UserListHolder(LayoutInflater.from(context).inflate(R.layout.user_item, parent, false));
  }

  @Override
  public void onBindViewHolder(UserListHolder holder, int position) {
    UserList.PlaylistBean playlistBean = playlist.get(position);
    Glide.with(context)
        .load(playlistBean.getCoverImgUrl())
        .into(holder.cover);
    holder.name.setText(playlistBean.getName());

    // 如果设置了回调，则设置点击事件
    if (mOnItemClickLitener != null) {
      holder.itemView.setOnClickListener(v -> {
        int pos = holder.getLayoutPosition();
        mOnItemClickLitener.onItemClick(holder.itemView, pos);
      });

      holder.itemView.setOnLongClickListener(v -> {
        int pos = holder.getLayoutPosition();
        mOnItemClickLitener.onItemLongClick(holder.itemView, pos);
        return false;
      });
    }
  }

  @Override
  public int getItemCount() {
    return playlist != null ? playlist.size() : 0;
  }

  class UserListHolder extends RecyclerView.ViewHolder {
    ImageView cover;
    TextView name;

    public UserListHolder(View view) {
      super(view);
      cover = view.findViewById(R.id.cover);
      name = view.findViewById(R.id.name);
    }
  }
}
